package com.hyd.issues.json;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.Result;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * Ajax Response
 *
 * @author yiding.he
 */
public class JsonResult implements Result {

    public static final JsonResult SUCCESS = new JsonResult(true);

    ///////////////////////////////////////////////////////

    private boolean successful;

    private String message;

    private Map<String, Object> data = new HashMap<String, Object>();

    public boolean isSuccessful() {
        return successful;
    }

    public String getMessage() {
        return message;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    ///////////////////////////////////////////////////////

    public JsonResult(boolean successful) {
        this.successful = successful;
    }

    public JsonResult(String key, Object value) {
        this(true);
        this.data.put(key, value);
    }

    //////////////////////////////////////////////////////

    public static JsonResult fail(String message) {
        JsonResult result = new JsonResult(false);
        result.message = message;
        return result;
    }

    public void execute(ActionInvocation invocation) throws Exception {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("application/json");
        
        PrintWriter writer = response.getWriter();
        writer.write(JsonUtil.toJson(this));
        writer.flush();
    }
}
